﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HU8.Helpers.Base;
using System.IO;
using Ionic.Zip;

namespace HU8.Helpers.Files
{
    /// <summary>
    /// PackageHelper
    /// 是用来帮助开发人员打包，解压他们的网站程序用的
    /// 作者：刘勇
    /// 日期：2011年9月20日
    /// </summary>
    public class PackageHelper
    {
        /// <summary>
        /// 打包HU8建站安装包
        /// \web.zip
        /// \script.sql
        /// 不包含素材
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="sqlPath"></param>
        /// <param name="destination"></param>
        public static JsonResponse PackInstaller(string filePath, string sqlPath, string dest, int version, bool isMajor, string notes = "")
        {
            string tempPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), Guid.NewGuid().ToString());
            JsonResponse response = new JsonResponse();
            Directory.CreateDirectory(tempPath);
            try
            {
                /**
                 * 发布日志
                 * */
                string releaseNote = string.Format("{0}\r\n{1}\r\n{2}", version, isMajor ? "稳定版" : "Beta版本", notes);
                FileHelper.CreateTextFile(tempPath, "release-note.txt", true, releaseNote);
                string releaseNotePath = Path.Combine(tempPath, "release-note.txt");

                /**
                 * 文件系统包
                 * */
                string zipPath = Path.Combine(tempPath, "web.zip");
                //Web.txt创建web.config.txt
                string webConfigXml = FileHelper.ReadTextFile(Path.Combine(filePath, "web.config"));
                FileHelper.CreateTextFile(filePath, "web.config.txt", true, webConfigXml);
                if (Directory.Exists(Path.Combine(filePath, "bin_temp")))
                {
                    Directory.Delete(Path.Combine(filePath, "bin_temp"), true); //删除文件夹
                }
                FileHelper.CreateFolder(filePath, "bin_temp");
                FileHelper.CopyContents(Path.Combine(filePath, "bin"), Path.Combine(filePath, "bin_temp")); //把文件从bin拷贝到bin_temp

                ZipHelper.GenerateZipFile(new List<string>() { filePath }, Path.Combine(tempPath, "web.zip"), "", BaseHelper.INSTALL_EXCEPTIONS, false); //压缩到web.zip
                
                File.Delete(Path.Combine(filePath, "web.config.txt")); //删除临时config文件
                Directory.Delete(Path.Combine(filePath, "bin_temp"), true); //删除临时bin_temp文件夹


                List<string> files = new List<string>()
                {
                    releaseNotePath,
                    zipPath
                };
                //如果没有数据库的话
                if (!string.IsNullOrEmpty(sqlPath))
                {
                    /**
                     * SQL安装文件：
                     * 必须为script.sql的文件名，
                     * 1，先复制到临时文件夹
                     * 2，重命名.sql文件
                     * **/
                    FileHelper.Relocate(new List<string>() { sqlPath }, tempPath, false);//拷贝到新的地址
                    FileInfo sqlFile = new FileInfo(sqlPath); //sql文件
                    sqlPath = Path.Combine(tempPath, sqlFile.Name); //sql 新路径
                    FileHelper.Rename(sqlPath, "script.sql"); //必须使用的名称
                    sqlPath = Path.Combine(tempPath, "script.sql");

                    files.Add(sqlPath);
                }

                /**
                 * 整体打包
                 * */
                ZipHelper.GenerateZipFile(files, dest, releaseNote); //生成安装包到指定文件夹
                response.success = true;
                response.message = "HU8建站安装包已经成功生成到："+ dest;
            }
            catch (Exception ex)
            {
                response.success = false;
                response.message = ex.Message;
            }
            //无论成功失败，删除临时文件夹
            Directory.Delete(tempPath, true);
            return response;
        }

        /// <summary>
        /// 解压安装包
        /// \version-no\web.zip
        /// \version-no\script.sql
        /// </summary>
        /// <param name="file"></param>
        /// <param name="dest"></param>
        public static JsonResponse UnpackInstaller(string file, string dest)
        {
            JsonResponse response = new JsonResponse();
            using (ZipFile zip = new ZipFile(file))
            {
                /**
                string versionNo = zip.Comment.Split('\n')[0]; //Release note 第一行就需要版本号
                dest = Path.Combine(dest, versionNo);
                 * ***/
                if (!Directory.Exists(dest))
                {
                    Directory.CreateDirectory(dest);
                }
                bool hasWebZip = false;
                bool hasScript = false;
                bool hasReleaseNotes = false;
                //确认一下zip的结构
                foreach (ZipEntry e in zip.Entries)
                {
                    if (e.FileName == "web.zip")
                    {
                        hasWebZip = true;
                    }
                    if (e.FileName == "script.sql")
                    {
                        hasScript = true;
                    }
                    if (e.FileName == "release-note.txt")
                    {
                        hasReleaseNotes = true;
                    }
                }
                if (hasWebZip)
                {
                    response = ZipHelper.UnzipFile(file, dest, true);
                }
                else
                {
                    response.message = "安装包结构不正确，解压失败";
                    response.success = false;
                }
            }
            return response;
        }
        //解压安装包
        public static JsonResponse Decompression(string file, string dest)
        {
            
            JsonResponse response = new JsonResponse();
            
            using (ZipFile zip = new ZipFile(file))
            {
                if (!Directory.Exists(dest))
                {
                    Directory.CreateDirectory(dest);
                }
                   response = ZipHelper.UnzipFile(file, dest, true);
                   response.success = true;
            }
            return response;
        }
       
    }
}
